#include "stdafx.h"
#include "InputValidator.h"




System::String^ InputValidator::validateFormInput(System::Windows::Forms::WebBrowser^ browser) {				
	System::Windows::Forms::HtmlElementCollection^ inputElems = browser->Document->GetElementsByTagName("input");
	System::Windows::Forms::HtmlElement^ inputElem;
	System::String^ inputType;
	System::String^ inputId;
	System::String^ inputValue;
	System::String^ inputValidValue;
	System::String^ errorMessage;
	System::Boolean^ jsReturnValue;
	cli::array<Object^> ^args = gcnew cli::array<Object^>(1);

	// Set a default error message
	errorMessage = "";

	// Iterate over the input elements
	for each(inputElem in inputElems) {
		inputId = inputElem->GetAttribute("id");
		inputValue = inputElem->GetAttribute("value");
		inputValidValue = inputElem->GetAttribute("valid_value");
		args[0] =  dynamic_cast<System::Object^>(inputId);
		inputType = inputElem->GetAttribute("type");
		if (inputType != "") {
			if (inputType == "text") {
				if (inputValidValue == "email") {
						jsReturnValue = dynamic_cast<System::Boolean^>(browser->Document->InvokeScript("validateEmail", args));
				}
				else if (inputValidValue == "numeric") {
						jsReturnValue = dynamic_cast<System::Boolean^>(browser->Document->InvokeScript("validateNumeric", args));
				}
				else if (inputValidValue == "alphabetic") {
						jsReturnValue = dynamic_cast<System::Boolean^>(browser->Document->InvokeScript("validateAlphabetic", args));
				}
				else if (inputValidValue == "alphanumeric") {
						jsReturnValue = dynamic_cast<System::Boolean^>(browser->Document->InvokeScript("validateAlphaNumeric", args));
				}
				else {
					// e.g inputValidValue == "all" or ""  -- just reset the boolean flag
					jsReturnValue = true;
				}
				
				if (jsReturnValue != nullptr) {
					if (!((bool)jsReturnValue)) {
						errorMessage = System::String::Concat(errorMessage, "Input [", inputValue, "] for ", inputId, " text field is invalid. This field requires ", inputValidValue, " data.\n"); 
					}
				}	
				else {
					// Throw exception?
				}
			}
		}
	}
	return errorMessage;
}